package com.hh.core.shiro;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.hh.admin.entity.SysUser;
import com.hh.core.shiro.entity.ShiroUser;
import com.hh.core.shiro.service.IShiroService;
import com.hh.core.shiro.util.ShiroUtil;

/**
 * 
 * @ClassName: ShiroUserRealm
 * @Description: TODO(自定义ShiroRealm)
 * @author hxn
 * @date 2018年1月15日 下午3:20:58
 *
 */
@Component
public class ShiroUserRealm extends AuthorizingRealm {

	@Autowired
	IShiroService shiroService;

	/**
	 * 权限认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		ShiroUser shiroUser = (ShiroUser) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.addRoles(shiroUser.getRoleCode());   //角色code
		info.addStringPermissions(shiroUser.getMenuList()); //菜单url
		return info;
	}

	/**
	 * 登录认证
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token){
		UsernamePasswordToken uptoken = (UsernamePasswordToken) token;
		SysUser sysUser = shiroService.getSysUser(uptoken.getUsername()); // 获取登录用户信息
		ShiroUser shiroUser = shiroService.getShiroUser(sysUser);
		SimpleAuthenticationInfo authenticationInfo = shiroService
				.getAuthenticationInfo(shiroUser, sysUser, super.getName());    //获取shiro的认证信息
		return authenticationInfo;
	}
	
	/**
	 * 设置认证加密方式
	 */
	@Override
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {
        HashedCredentialsMatcher md5CredentialsMatcher = new HashedCredentialsMatcher();
        md5CredentialsMatcher.setHashAlgorithmName(ShiroUtil.hashAlgorithmName);
        md5CredentialsMatcher.setHashIterations(ShiroUtil.hashIterations);
        super.setCredentialsMatcher(md5CredentialsMatcher);
    }

}
